package com.oss.weixin.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import cn.hutool.core.lang.Validator;
import com.feizhou.swagger.annotation.Api;
import com.feizhou.swagger.annotation.ApiOperation;
import com.jfinal.kit.HashKit;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.JsTicket;
import com.jfinal.weixin.sdk.api.JsTicketApi;
import com.jfinal.weixin.sdk.api.JsTicketApi.JsApiType;
import com.jfinal.weixin.sdk.jfinal.ApiController;
import com.oss.view.InvokeResult;

@Api(tag = "weixin", description = "微信 模块接口")
public class ShareController extends ApiController {

    @ApiOperation(url = "/share", tag = "weixin", httpMethod = "get", description = "获取微信分享的参数")
    public void index() {

        JsTicket jsApiTicket = JsTicketApi.getTicket(JsApiType.jsapi);
        String jsapi_ticket = jsApiTicket.getTicket();
        String nonce_str = create_nonce_str();

        String url = "http://qinqing.ydcycloud.com/employee/index.html";

//        if (Validator.isEmpty(url)) {
//            // 注意 URL 一定要动态获取，不能 hardcode.
//            url = "http://" + getRequest().getServerName() // 服务器地址
//                    // + ":"
//                    // + getRequest().getServerPort() //端口号
//                    + getRequest().getContextPath() // 项目名称
//                    + getRequest().getServletPath();// 请求页面或其他地址
//            String qs = getRequest().getQueryString(); // 参数
//            if (qs != null) {
//                url = url + "?" + (getRequest().getQueryString());
//            }
//        }

        String timestamp = create_timestamp();
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        // 注意这里参数名必须全部小写，且必须有序
        String str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url="
                + url;

        String signature = HashKit.sha1(str);

        Map<String, Object> item = new HashMap<>();

        item.put("appId", ApiConfigKit.getApiConfig().getAppId());
        item.put("nonceStr", nonce_str);
        item.put("timestamp", timestamp);
        item.put("url", url);
        item.put("signature", signature);
        item.put("jsapi_ticket", jsapi_ticket);

        renderJson(InvokeResult.success(item));

    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    public static void main(String[] args) {
        // System.out.println(createNonceStr().length());
        System.out.println(System.currentTimeMillis());
        System.out.println(HashKit.sha1(
                "jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW&timestamp=1414587457&url=http://mp.weixin.qq.com?params=value"));
    }
}
